package com.ascentive.finallyfast.quickboost;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.ascentive.finallyfast.deepclean.DeepCleanPage;
import com.ascentive.finallyfast.quickboost.QBTaskListAdapters.QBProcessListAdapter;
// import com.ascentive.finallyfast.quickboost.QBTaskListAdapters.QBTasksListAdapter;
import com.ascentive.finallyfast.R;

public class QuickBoostPage extends ListActivity{
	
		static final private int CLOSE_APPLICATION_DIALOG = 1;
		public static final boolean DEBUG = true;
	    public static final String TAG = "FreeTaskManager";
	    private QBProcessInfo pinfo = null;
	    ActivityManager am = null;
	    private QBPackagesInfo packageinfo = null;
	    private PackageManager pm = null;
	    private ProgressBar progressBar = null;

	    private static final int STAT_TASK = 0;
	    private static final int STAT_SERVICE = 1;
	    private static final int STAT_SYSTEM = 2;
	    protected static final String ACTION_LOAD_FINISH = "com.ascentive.finallyfast.quickboost.ACTION_LOAD_FINISH";

	    private int currentStat = STAT_TASK;
	    private QBProcessListAdapter adapter = null;
	    private BroadcastReceiver loadFinish = new LoadFinishReceiver();
	    private ArrayList<QBDetailProcess> listApps = null;
	    private ArrayList<QBDetailTask> listTasks = null;
	    private ArrayList<String> listServices = null;
	    
	    ProgressDialog loadAppListProgress = null;
	    
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.quick_boost_list);
		
		TextView tv = (TextView)this.findViewById(R.id.hedingtext);
		tv.setTextColor(Color.BLACK);
		
		System.out.println("QuickBoost onCreate");
		
		ListView lv = getListView();
		
		lv.setBackgroundResource(R.drawable.list_control_bg2);
		lv.setCacheColorHint(Color.TRANSPARENT);
		
        am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        pm = this.getApplicationContext().getPackageManager();
        packageinfo = new QBPackagesInfo(this);
        
        customResume();
        
        }
	
	/** Creating Alert Dialog when clear button is pressed */
	@Override
	protected Dialog onCreateDialog(int id) {
		
		LayoutInflater li;
		
		switch (id) {
		case CLOSE_APPLICATION_DIALOG:
			
			li = LayoutInflater.from(this);
			View selectdurationView = li.inflate(R.layout.close_app_dialog, null);
			AlertDialog.Builder selectDurationDialogBuilder = new AlertDialog.Builder(this);
			// Set Title
			//selectDurationDialogBuilder.setTitle("Select duration");
			// selectDurationDialogBuilder.setIcon(R.drawable.top_of_dialog);			
			selectDurationDialogBuilder.setView(selectdurationView);

			//ImageView iv = (ImageView)selectdurationView.findViewById(R.id.titleImage);
			//iv.setBackgroundDrawable(d)
			
			AlertDialog selectDurationAlertDialog = selectDurationDialogBuilder.create();
			// Set positive button
			selectDurationAlertDialog.setButton("Yes",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
			// Set negative button
			selectDurationAlertDialog.setButton2("No",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
			return selectDurationAlertDialog;
			
		default:
			break;
		}
		return null;
	}
	// @Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		// Get the item that was clicked
		Object o = this.getListAdapter().getItem(position);
		String keyword = o.toString();
		Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
				.show();
	}
	
	//ListView getListView() {
      //  return getListView();
        // (ListView) this.findViewById(R.id.list);
    // }
    
    public void refresh() {
        setProgressBarIndeterminateVisibility(true);
        
        loadAppListProgress = new ProgressDialog(this);
        loadAppListProgress.setIndeterminate(true);
        loadAppListProgress.setMessage("Loading");
        loadAppListProgress.setCancelable(true);
        loadAppListProgress.show();

//		final Handler handler = new Handler() {
//			public void handleMessage(Message msg) {
//				loadAppListProgress.dismiss();
//            	loadAppListProgress = null;
//            	
//				// showDialog(CLEAN_STATUS_DIALOG);
//			}
//		};
		
        if (currentStat == STAT_TASK) {

            Thread t = new Thread(new Runnable() {

                // @Override
                public void run() {
                	
                    pinfo = new QBProcessInfo();
                    getRunningProcess();
                    getRunningTask();
                    
                    Intent in = new Intent(ACTION_LOAD_FINISH);
                    QuickBoostPage.this.sendBroadcast(in);
                }

            });
            t.start();
        }
    }

    public QBProcessInfo getProcessInfo() {
        return pinfo;
    }

    public QBPackagesInfo getPackageInfo() {
        return packageinfo;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // System.out.println("change");
    }

    // @Override
    protected void customResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter(ACTION_LOAD_FINISH);
        this.registerReceiver(loadFinish, filter);
        packageinfo = new QBPackagesInfo(this);
        // Make sure the progress bar is visible

        System.out.println("QuickBoost customRefresh");
        
        refresh();
    }

    @SuppressWarnings("unchecked")
    public void getRunningProcess() {
        List<RunningAppProcessInfo> list2 = am.getRunningAppProcesses();
        listApps = new ArrayList<QBDetailProcess>();
        for (RunningAppProcessInfo ti : list2) {
            //System.out.println(ti.processName + "/" + ti.pid + "/" + ti.lru + "/" + ti.importance
             //+ "/"
             //+ Arrays.toString(ti.pkgList) + "\n\n");
            if (ti.processName.equals("system") || ti.processName.equals("com.android.phone")) {
            	
            	System.out.println(ti.processName + "/" + ti.pid + "/" + ti.lru + "/" + ti.importance
                + "/"
                + Arrays.toString(ti.pkgList) + "\n\n");
                continue;
                
            }
            QBDetailProcess dp = new QBDetailProcess(this, ti);
            dp.fetchApplicationInfo(packageinfo);
            dp.fetchPackageInfo();
            dp.fetchPsRow(pinfo);
            // dp.fetchTaskInfo(this);
            if (dp.isGoodProcess()) {
                listApps.add(dp);
                // System.out.println(Arrays.toString(dp.getPkginfo().activities));
            }
        }
        Collections.sort(listApps);
        adapter = new QBProcessListAdapter(this);
    }

    // public RunningTaskInfo getTaskInfo(String name) {
    // if (tasklist != null) {
    // for (RunningTaskInfo ti : tasklist) {
    // if (ti.baseActivity.getPackageName().equals(name)) {
    // return ti;
    // }
    // }
    // }
    // return null;
    // }

    public void getRunningTask() {

        List<RunningTaskInfo> list = am.getRunningTasks(100);
        System.out.println("--------"+list.size());
        listTasks = new ArrayList<QBDetailTask>();
        for (RunningTaskInfo ti : list) {
            System.out.println(ti.baseActivity.getPackageName() + "/" + ti.baseActivity.getClassName() + "/"
                    + ti.id);
            QBDetailTask dp = new QBDetailTask(this, ti);
            
			String pkgName = ti.baseActivity.getPackageName();
			String className = ti.baseActivity.getClassName();
            
            // dp.fetchTaskInfo(packageinfo);
            // String n = dp.getTitleTask();
            // dp.fetchPsRow(pinfo);
            // dp.fetchTaskInfo(packageinfo);
            //if (dp.isGoodProcess()) {
            	listTasks.add(dp);
            // }
            // listTasks.add(ti.baseActivity.getPackageName());
        }
        
        //ListAdapter adapter = new QBTasksListAdapter(this, list);
        // tadapter = new QBTasksListAdapter(this, list);
        // getListView().setAdapter(tadapter);
       
//        List<RunningServiceInfo> list3 = am.getRunningServices(100);
//        System.out.println("--------"+list3.size());
//        listServices = new ArrayList<String>();
//        for (RunningServiceInfo tii : list3) {
//            System.out.println(tii.service.getPackageName() + "/" + tii.service.getClassName());
//            listServices.add(tii.service.getPackageName());
//        }
        /*
        MemoryInfo outInfo = new MemoryInfo();
        am.getMemoryInfo(outInfo);
        System.out.println(outInfo.availMem);
        */
        // return list;
    }

    // am.restartPackage("org.freecoder.securesms");

    // Intent i = new Intent(Intent.ACTION_MAIN);
    // i.setClassName("org.freecoder.securesms", "org.freecoder.securesms.SecureSms");
    // startActivity(i);

    private class LoadFinishReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context ctx, Intent intent) {
        	QuickBoostPage.this.setProgressBarIndeterminateVisibility(false);
        	loadAppListProgress.dismiss();
        	loadAppListProgress = null;
        	
        	// Applications section
        	ArrayAdapter<QBDetailProcess> appsAdapter = new ArrayAdapter<QBDetailProcess>(QuickBoostPage.this, R.layout.list_main, listApps);
        	adapter.addSection("Applications", appsAdapter);
        	
//        	ArrayAdapter<QBDetailProcess> apps1Adapter = new ArrayAdapter<QBDetailProcess>(QuickBoostPage.this, R.layout.list_main, listApps);
//        	adapter.addSection("Tasks", apps1Adapter);
        	
        	ArrayAdapter<QBDetailTask> taskAdapter = new ArrayAdapter<QBDetailTask>(QuickBoostPage.this, R.layout.list_main_text, listTasks);
        	adapter.addSection("Tasks", taskAdapter);
        	
        	// ArrayAdapter<QBDetailService> appsAdapter = new ArrayAdapter<QBDetailService>(QuickBoostPage.this, R.layout.list_main, listApps);
        	// adapter.addSection("Services", listServices);
			
        	QuickBoostPage.this.getListView().setAdapter(adapter);
        	
        	// progressBar.setVisibility(ProgressBar.GONE);
        	QuickBoostPage.this.getListView().setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    /*  
                	if (currentStat == STAT_TASK) {
                        QBDetailProcess dp = listdp.get(arg2);
                         MiscUtil.getTaskMenuDialog(QuickBoostPage.this, dp).show();
                    }*/
                    //System.out.println(arg2);
                }
                
            });
        }
    }
    

    @Override
    protected void onPause() {
        super.onPause();
        if(loadFinish != null)
        {
        	this.unregisterReceiver(loadFinish);
        	loadFinish = null;
        }
    }
}
